package xyc.szk.eljstl.servlet;

import com.sun.deploy.util.SessionState;
import org.apache.commons.beanutils.BeanUtils;
import xyc.szk.eljstl.pojo.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8"); //post请求时 接收参数要指定编码 否则会乱码 get由tomcat8及以上会自动搞定
        //登录验证逻辑
        //1、获取提交 的表单参数
        //String userName = req.getParameter("userName");
        //String userPwd = req.getParameter("userPwd");
        //
        //System.out.println("userName+userPwd = " + userName +"--"+ userPwd);
        //map的形式
        Map<String, String[]> map = req.getParameterMap(); // key有：userName,userPwd
        //map.forEach((k,v)-> System.out.println(k+"-"+v));//lambda表达式
        //表单元素封装到一个javabean中，因为java是面向对象编程 所以一切以对象作为基础
        Users u = new Users(); //id1,userName,userPwd,age
        //u.setUserName(map.get("userName")[0]);//这样写相当 麻烦
        //u.setUserPwd(map.get("userPwd")[0]);
        //beanUtils工具类将map中key和u这个bean对象的属性名称 相同的value值给相应名称 的属性赋值
        try {
            BeanUtils.populate(u, map);//将map所有key-value对给u这个bean相应属性赋值
            System.out.println("u = " + u);
            //将用户名显示面页面上
           //将整个登录用户的信息：即这个javaBean对象 u全部存放到session域(同一个会话的多个请求)中
            req.getSession().setAttribute("loginInfo",u);
            //将当前的请求重定向到页面success.jsp
            resp.sendRedirect(req.getContextPath()+"/success.jsp"); //req.getContextPath()== "/07"


        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
